using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace Tomahawk.Runtime.Serialization
{

    public class SerializableList<T> : List<T>, IXmlSerializable
    {
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            bool wasEmpty = reader.IsEmptyElement;
            reader.Read();

            if (wasEmpty) return;

            while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
            {
                if (reader.NodeType == System.Xml.XmlNodeType.Element)
                {
                    //get the propper type from the type attribute, or use (T) if none is specified
                    string sType = reader.GetAttribute("type");
                    Type tType = null;
                    if ((sType == null) || (sType == ""))
                    {
                        tType = typeof(T);
                    }
                    else
                        tType = Type.GetType(sType);

                    //deserialize the array item
                    XmlSerializer valueSerializer = new XmlSerializer(tType);
                    T value = (T)valueSerializer.Deserialize(reader);

                    this.Add(value);
                }
                reader.MoveToContent();
            }
            reader.ReadEndElement();
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            foreach (T value in this)
            {
                //by default serialize as the base class
                Type tType = typeof(T);

                //but if concrete class supports ISerializableDerivableClass, use the concrete type instead
                if (typeof(ISerializableDerivableType).IsAssignableFrom(tType)) tType = value.GetType();

                XmlSerializer valueSerializer = new XmlSerializer(tType);
                valueSerializer.Serialize(writer, value);
            }
        }

    }

}
